﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace _00365.Configurations.Controls
{
	public partial class RolesForm : System.Web.UI.UserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				chlFeatures.DataSource = Biz.Features.GetAll();
				chlFeatures.DataBind();
			}
			if (!IsPostBack && !string.IsNullOrEmpty(Request.QueryString["id"]))
			{
				var group = Biz.UserGroups.Get(Guid.Parse(Request.QueryString["id"]));
				if(group!= null)
					BindForm(group);
			}
		}

		private void BindForm(Data.UserGroup group)
		{
			txtName.Text = group.Name;
			ddlActive.SelectedValue = group.Active.ToString().ToLower();
			foreach (Data.Permission item in group.Permission)
			{
				chlFeatures.Items.FindByValue(item.Id_Feature.ToString()).Selected = true;
			}
		}

		protected void click_btnSave(object sender, EventArgs e)
		{
			try
			{
				var group = !string.IsNullOrEmpty(Request.QueryString["id"]) ? Biz.UserGroups.Get(Guid.Parse(Request.QueryString["id"])) : new Data.UserGroup();
				if (string.IsNullOrEmpty(group.Name))
					group.Id = Guid.NewGuid();
				group.Name = txtName.Text;
				group.Active = bool.Parse(ddlActive.SelectedValue);
                
                if (group.Permission.Count > 0)
                {
                    group.Permission.Load();
                    List<Data.Permission> oldPerms = Biz.UserGroups.Get(Guid.Parse(Request.QueryString["id"])).Permission.ToList();
                    foreach (Data.Permission item in oldPerms)
                    {
                        group.Permission.Remove(item);
                    }
                }

				foreach (ListItem item in chlFeatures.Items)
				{
					if (item.Selected)
						group.Permission.Add(new Data.Permission() { Id = Guid.NewGuid(), Id_Feature = Guid.Parse(item.Value), Id_UserGroup = group.Id });					
				}
				//if edit then update form data
				if (!string.IsNullOrEmpty(Request.QueryString["id"]))
				{					
					Biz.UserGroups.Update(group);
				}
				//if new just insert the data
				else
				{
					Biz.UserGroups.Add(group);
				}
			}
			catch (Exception ex)
			{
				
				throw ex;
			}
		}
	}
}